/*
 * Created by Jaren at 2021/11/28 15:12
 */
import 'dart:math';
import 'dart:typed_data';

import 'package:inmotion_protocol/common/product_version.dart';
import 'package:inmotion_protocol/util/byte_util.dart';

class VersionUtils {
  static bool higherOrEquals(String version1, String version2) {
    List<int> versions1 = version(version1);
    List<int> versions2 = version(version2);
    int loopCount = max(versions1.length, versions2.length);
    for (int i = 0; i < loopCount; i++) {
      if (versions1.length <= i) return false;
      if (versions2.length <= i) return true;
      if (versions1[i] > versions2[i]) return true;
      if (versions1[i] < versions2[i]) return false;
      continue;
    }
    return true;
  }

  static bool lower(String version1, String version2) {
    return higherOrEquals(version2, version1);
  }

  static bool equals(String v1, String v2) {
    return v1 == v2;
  }

  static List<int> version(String v) {
    RegExp reg = RegExp(r"(\d+)\.(\d+)\.(\d+)");
    List<int> versions = [];
    Iterable<RegExpMatch> iterable = reg.allMatches(v);
    if (iterable.isEmpty) return versions;

    RegExpMatch match = iterable.first;
    for (int i = 0; i < match.groupCount; i++) {
      versions.add(int.tryParse(match.group(i + 1)!) ?? 0);
    }
    return versions;
  }

  static Uint8ClampedList fwVersionText2Bytes(String version) {
    Iterable<RegExpMatch> matches = RegExp(r"(\d+)\.(\d+)\.(\d+)").allMatches(version);

    if (matches.length != 1) return Uint8ClampedList(0);

    Uint8ClampedList bytes = Uint8ClampedList(Version.singleVersionLength);

    List<int> intVersion = [];
    RegExpMatch match = matches.first;
    for (int i = 0; i < match.groupCount; i++) {
      intVersion.add(int.tryParse(match.group(i + 1)!) ?? 0);
    }

    bytes[bytes.length - 1] = intVersion[0];
    bytes[bytes.length - 1 - 1] = intVersion[1];
    ByteUtil.num2BytesLe(intVersion[2], 2, bytes, 0);

    return bytes;
  }
}
